package com.tuyue.police.WebSocked;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: 王金海
 * @Description:
 * @Date: Created by Administrator on 2018/1/22.
 * @Modified By:
 */
@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class MyWebSocked {


    private Session session;

    private static CopyOnWriteArraySet<MyWebSocked> myWebSockeds=new CopyOnWriteArraySet<>();
    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        myWebSockeds.add(this);
        log.info("【MyWebSocked消息】 有新的连接， 总数：{}",myWebSockeds.size());
    }

    @OnClose
    public void onClose(){
        myWebSockeds.remove(this);
        log.info("【MyWebSocked消息】 连接断开， 总数：{}",myWebSockeds.size());
    }

    @OnMessage
    public void onMessage(String msg){
        log.info("【MyWebSocked消息】 收到消息， 内容是：{}",msg);
    }


    public void sendMsg(String msg){
        for (MyWebSocked myWebSocked : myWebSockeds) {
            log.error("【MyWebSocked消息】 发送消息， 内容是：{}",msg);
            try {
                myWebSocked.session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                log.error("【MyWebSocked消息】 发送消息异常：{}",msg);
                e.printStackTrace();
            }
        }


    }
}
